<template>
  <el-dialog
    v-model="props.closeDialog"
    title="关闭维修"
    :show-close="false"
    width="30%"
  >
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="关闭维修原因" prop="closeReason">
        <el-input
          v-model="form.closeReason"
          autocomplete="off"
          type="textarea"
          row="4"
          maxlength="100"
          placeholder="请输入原因"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="相关照片" porp="repairImg">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          :action="`${proxy.$http}/user/upload/uploadFile`"
          :http-request="(resp: any) => { return handleUpload(resp, 15) }"
          limit="9"
          :headers="headers"
          accept=".png,.jpg,.jpeg,.mp4"
          :show-file-list="false"
          multiple
          :before-upload="(resp: any) => { return fileBeforeUpload(resp, 15) }"
          :on-error="(resp: any) => { return fileError(resp, 15) }"
          :on-exceed="handleExceed"
          :disabled="fileList.length >= 9"
        >
          <el-button type="primary" :disabled="fileList.length >= 9"
            >上传图片或视频</el-button
          >
        </el-upload>
        <div class="tips" style="margin: auto auto 0px 5px">
          可传视频或图片，最多9个
        </div>
      </el-form-item>
      <el-form-item>
        <div style="display: flex; flex-flow: row wrap">
          <div v-for="(item, index) in filePictrueList">
            <el-image
              style="width: 94px; height: 84px; padding: 0 5px"
              :src="item"
              :zoom-rate="1.2"
              v-if="
                item.substring(item.indexOf('?') - 3, item.indexOf('?')) ==
                  'jpg' ||
                item.substring(item.indexOf('?') - 3, item.indexOf('?')) ==
                  'png' ||
                item.substring(item.indexOf('?') - 3, item.indexOf('?')) ==
                  'peg'
              "
              :preview-src-list="filePictrueList"
              :initial-index="index"
              fit="cover"
            />
            <div style="text-align: center">
              <el-button type="text" @click="deletePic(item, index, 1)"
                >删除</el-button
              >
            </div>
          </div>
          <div v-for="(item, index) in fileVedioList">
            <video
              :src="item"
              class="avatar"
              controls="controls"
              style="width: 94px; height: 84px; padding: 0 5px"
              @play="handleFullScreen"
            ></video>
            <div style="text-align: center">
              <el-button type="text" @click="deletePic(item, index, 2)"
                >删除</el-button
              >
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="验证人" porp="repairImg" prop="verifyUserId">
        <el-select
          v-model="form.verifyUserId"
          class="m-2"
          placeholder="请选择验证人"
          style="width: 100%"
          clearable
          filterable
          @change="userChange"
        >
          <el-option
            v-for="item in verifyUsers"
            :key="item.id"
            :label="item.realName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ElLoading,
  ElMessage,
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile
} from 'element-plus'
import { ref, reactive, getCurrentInstance } from 'vue'
import { getDirectorListApi, uploadFileApi } from '/@/api/publicApi'
import { closeRepairApi } from '/@/api/repair'
import { Session } from '/@/utils/storage'
const { proxy } = getCurrentInstance() as any
const props = defineProps({
  closeDialog: Boolean,
  closeId: String
})
const emit = defineEmits(['closeCancel', 'closeSubmit'])
const formLabelWidth = ref('120px')
const verifyUsers = ref<any>([])
const ruleFormRef = ref<FormInstance>()
const form = ref({
  closeReason: '',
  closePictures: '',
  verifyUserId: '',
  verifyUserName: ''
})

const rules = reactive<FormRules>({
  closeReason: [{ required: true, message: '请输入关闭原因', trigger: 'blur' }],
  verifyUserId: [{ required: true, message: '请选择验证人', trigger: 'change' }]
})

//图片视频上传
//图片上传
const userInfo = Session.get('token')
const token = userInfo ? userInfo : ''
const headers = ref({
  'Content-Type': 'multipart/form-data',
  'Api-User-Token': token
})
let uploadLoading = ref([false, false, false])
const vedioUrl = ref('')
const fileList = ref<UploadUserFile[]>([])
const filePictrue = ref<any>([])
const filePictrueList = ref<any>([])
const fileVedioList = ref<any>([])
const handleUpload = (file: any, type: any) => {
  if (filePictrueList.value.length >= 9) {
    ElMessage.warning('已达最大上传限制')
  } else {
    const loading = ElLoading.service({
      lock: true,
      text: '上传中',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    uploadFileApi({ type: 15, file: file.file }).then((res) => {
      filePictrue.value.push(res.data.fileIds[0])
      if (
        res.data.fileIds[0].substring(
          res.data.fileIds[0].indexOf('?') - 3,
          res.data.fileIds[0].indexOf('?')
        ) == 'jpg' ||
        res.data.fileIds[0].substring(
          res.data.fileIds[0].indexOf('?') - 3,
          res.data.fileIds[0].indexOf('?')
        ) == 'png' ||
        res.data.fileIds[0].substring(
          res.data.fileIds[0].indexOf('?') - 3,
          res.data.fileIds[0].indexOf('?')
        ) == 'peg'
      ) {
        filePictrueList.value.push(res.data.fileIds[0])
        ElMessage.success('图片上传成功！')
      } else {
        fileVedioList.value.push(res.data.fileIds[0])
        ElMessage.success('视频上传成功！')
      }
      uploadLoading.value[type] = false
      loading.close()
    })
  }
}

const fileError = (err: any, type: any) => {
  ElMessage.error('项目文件上传失败！')
  fileList.value = []
  uploadLoading.value[type] = false
}
const fileBeforeUpload = (rawFile: any, type: any) => {
  // console.log('rawFile', rawFile)
  uploadLoading.value[type] = true
}
// 上传前，定义超出限制时的行为
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning('最多只能上传9个文件！')
}

const deletePic = (val: any, index: any, type: any) => {
  if (type == 1) {
    filePictrueList.value.splice(index, 1)
  } else {
    fileVedioList.value.splice(index, 1)
  }
  filePictrue.value.forEach((item: any, i: any) => {
    if (item == val) {
      fileList.value.splice(i, 1)
    }
  })
  filePictrue.value = filePictrue.value.filter((item: any) => item != val)
}

const handleFullScreen = (e: any) => {
  launchFullscreen(e.target)
}

const launchFullscreen = (element: any) => {
  //此方法不可以在異步任務中執行，否則火狐無法全屏
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen()
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen()
  } else if (element.oRequestFullscreen) {
    element.oRequestFullscreen()
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen()
  } else {
    var docHtml = document.documentElement
    var docBody = document.body
    var videobox = element
    var cssText = 'width:100%;height:100%;overflow:hidden;'
    docHtml.style.cssText = cssText
    docBody.style.cssText = cssText
    videobox.style.cssText = cssText + ';' + 'margin:0px;padding:0px;'
    document.IsFullScreen = true
  }
}

const cancel = (formEl: FormInstance | undefined) => {
  filePictrue.value = []
  filePictrueList.value = []
  fileVedioList.value = []
  if (!formEl) return
  formEl.resetFields()
  emit('closeCancel')
}

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      form.value.closePictures = filePictrue.value.join(',')
      Reflect.set(form.value, 'id', props.closeId)
      closeRepairApi(form.value).then((res) => {
        if (res.code == 0) {
          ElMessage.success('关闭成功')
          filePictrue.value = []
          filePictrueList.value = []
          fileVedioList.value = []
          emit('closeSubmit')
        }
      })
    }
  })
}

const getDirectorList = () => {
  getDirectorListApi(2).then((res) => {
    if (res.code == 0) {
      verifyUsers.value = res.data
    }
  })
}
getDirectorList()

const userChange = (val: any) => {
  verifyUsers.value.forEach((i: any) => {
    if (i.id == val) {
      form.value.verifyUserName = i.realName
    }
  })
}
</script>
<style scoped lang="scss"></style>
